<template>
  <div 
    ref="containerRef"
    class="message-list"
    @scroll="onScroll"
    @mouseover="handleMessageMouseOver"
    @mouseleave="handleMessageMouseLeave"
  >
    <!-- 加载状态 -->
    <div
      v-if="loading"
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-spinner="el-icon-loading"
      class="loading-container"
    ></div>
    
    <!-- 结束提示 -->
    <div
      v-show="endFlag || (messages.length <= 0 && loading === false)"
      class="end-message-container"
    >
      <span class="end-message-text">慢点、到顶了</span>
    </div>
    
    <!-- 单聊消息列表 -->
    <div v-if="isSingleChat">
      <MessageItem
        v-for="(message, index) in messages"
        :key="message.id || message.tempId || (message.createTime + '-' + index)"
        :message="message"
        :message-handler-flag="messageHandlerFlag"
        :playing-voice-id="playingVoiceId"
        :default-avatar="defaultAvatar"
        @avatar-click="handleAvatarClick"
        @command="handleCommand"
        @get-content="handleGetContent"
        @dropdown-close="handleDropdownClose"
        @play-voice="handlePlayVoice"
        @download-file="handleDownloadFile"
        @open-app-link="handleOpenAppLink"
        @resend="handleResend"
        @send-friend-check="handleSendFriendCheck"
        @edit="handleEdit"
      />
    </div>
    
    <!-- 群聊消息列表 -->
    <div v-else>
      <MessageItem
        v-for="(message, index) in messages"
        :key="message.id || message.tempId || (message.createTime + '-' + index)"
        :message="message"
        :message-handler-flag="messageHandlerFlag"
        :playing-voice-id="playingVoiceId"
        :default-avatar="defaultAvatar"
        @avatar-click="handleAvatarClick"
        @command="handleCommand"
        @get-content="handleGetContent"
        @dropdown-close="handleDropdownClose"
        @play-voice="handlePlayVoice"
        @download-file="handleDownloadFile"
        @open-app-link="handleOpenAppLink"
        @resend="handleResend"
        @send-friend-check="handleSendFriendCheck"
        @edit="handleEdit"
      />
    </div>
  </div>
</template>

<script>
import MessageItem from './MessageItem.vue';

export default {
  name: 'MessageList',
  components: {
    MessageItem
  },
  props: {
    messages: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    endFlag: {
      type: Boolean,
      default: false
    },
    isSingleChat: {
      type: Boolean,
      default: true
    },
    messageHandlerFlag: {
      type: [String, Number],
      default: null
    },
    playingVoiceId: {
      type: [String, Number],
      default: null
    },
    defaultAvatar: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      scrollTop: 0,
      isScrolling: false,
      shouldAutoScroll: true
    };
  },
  watch: {
    // 监听消息数量变化，自动滚动到底部
    'messages.length': {
      handler(newLength, oldLength) {
        // 只有在消息数量增加且用户没有手动滚动时才自动滚动
        if (newLength > (oldLength || 0) && this.shouldAutoScroll) {
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 50);
          });
        }
      }
    }
  },
  methods: {
    // 滚动处理
    onScroll(event) {
      this.scrollTop = event.target.scrollTop;
      this.isScrolling = true;
      
      // 检查用户是否滚动到底部附近
      const { scrollTop, scrollHeight, clientHeight } = event.target;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 50;
      
      // 如果用户滚动到底部附近，启用自动滚动；否则禁用
      this.shouldAutoScroll = isNearBottom;
      
      // 节流处理滚动事件
      clearTimeout(this.scrollTimer);
      this.scrollTimer = setTimeout(() => {
        this.isScrolling = false;
        this.$emit('scroll', event);
      }, 100);
    },
    
    // 事件委托 - 优化性能
    handleMessageMouseOver(event) {
      const messageElement = event.target.closest('[data-message-id]');
      if (messageElement) {
        const messageId = messageElement.getAttribute('data-message-id');
        this.$emit('message-enter', messageId);
      }
    },
    
    handleMessageMouseLeave(event) {
      const messageElement = event.target.closest('[data-message-id]');
      if (messageElement) {
        this.$emit('message-leave');
      }
    },
    
    // 头像点击
    handleAvatarClick(message) {
      this.$emit('avatar-click', message);
    },
    
    // 消息操作
    handleCommand(command, message) {
      this.$emit('command', command, message);
    },
    
    // 获取内容
    handleGetContent(content) {
      this.$emit('get-content', content);
    },
    
    // 下拉菜单关闭
    handleDropdownClose(event) {
      this.$emit('dropdown-close', event);
    },
    
    // 播放语音
    handlePlayVoice(voiceUrl, msgId) {
      this.$emit('play-voice', voiceUrl, msgId);
    },
    
    // 下载文件
    handleDownloadFile(fileUrl, fileName) {
      this.$emit('download-file', fileUrl, fileName);
    },
    
    // 打开应用链接
    handleOpenAppLink(url) {
      this.$emit('open-app-link', url);
    },
    
    // 重新发送
    handleResend(message) {
      this.$emit('resend', message);
    },
    
    // 发送好友验证
    handleSendFriendCheck() {
      this.$emit('send-friend-check');
    },
    
    // 编辑消息
    handleEdit(content) {
      this.$emit('edit', content);
    },
    
    // 滚动到底部
    scrollToBottom() {
      // 使用多重nextTick确保DOM完全渲染
      this.$nextTick(() => {
        this.$nextTick(() => {
          if (this.$refs.containerRef) {
            const container = this.$refs.containerRef;
            const scrollHeight = container.scrollHeight;
            const clientHeight = container.clientHeight;
            
            // 如果容器还没有内容，延迟重试
            if (scrollHeight <= clientHeight) {
              setTimeout(() => {
                this.scrollToBottom();
              }, 100);
              return;
            }
            
            container.scrollTop = scrollHeight;
            // 确保自动滚动状态为true
            this.shouldAutoScroll = true;
          } else {
            // 容器引用不存在，延迟重试
            setTimeout(() => {
              this.scrollToBottom();
            }, 100);
          }
        });
      });
    },
    
    // 强制滚动到底部（忽略用户滚动状态）
    forceScrollToBottom() {
      this.shouldAutoScroll = true;
      this.scrollToBottom();
    },
    
    // 滚动到顶部
    scrollToTop() {
      this.$nextTick(() => {
        if (this.$refs.containerRef) {
          this.$refs.containerRef.scrollTop = 0;
        }
      });
    }
  },
  mounted() {
    // 组件挂载后滚动到底部，使用延迟确保DOM完全渲染
    setTimeout(() => {
      this.scrollToBottom();
    }, 200);
  },
  beforeDestroy() {
    // 清理定时器
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer);
    }
  }
};
</script>

<style scoped>
.message-list {
  height: 100%;
  width: 100%;
  overflow-y: auto;
  position: relative;
  padding: 0 10px;
  flex: 1;
}

.loading-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
}

.end-message-container {
  text-align: center;
  padding: 20px 0;
}

.end-message-text {
  color: #999999;
  font-size: 13px;
}

/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: transparent;
}

.message-list::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 0, 0, 0.3);
}

/* 性能优化 */
.message-list {
  contain: layout style paint;
  transform: translateZ(0); /* 启用硬件加速 */
}
</style>